﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;
using System.ServiceModel.Channels;
using System.ServiceModel;

namespace Cherry.Agile.ServiceModel.Interceptor {
    public sealed class DefaultEndpointPolicy : IEndpointPolicy {

        internal static readonly IEndpointPolicy EndpointPolicy = new DefaultEndpointPolicy();


        static Lazy<Binding> _lazyBinding = new Lazy<Binding>(() => new NetTcpBinding(""));

        public Binding DefaultBinding { get { return _lazyBinding.Value; } }

        public string GetAddress(Type contract,string baseAddress) {
            if (string.IsNullOrEmpty(baseAddress))
                return contract.FullName;
            return baseAddress.TrimEnd('/') + "/" + contract.FullName;
        }

        public ServiceEndpoint CreateServiceEndpoint(Type implementedContract, string basicAddress) {
            var address = new EndpointAddress(GetAddress(implementedContract,basicAddress));
            return new ServiceEndpoint(ContractDescription.GetContract(implementedContract),
                                        DefaultBinding, address);
        }
    }
}
